<?php

class Kd_Collection_Array extends Kd_Collection_Enumerator implements ArrayAccess {

    protected $source = array();

    public function __construct($source = array()) {
        parent::__construct($source);
    }

    public function get($key, $default = '') {
        if(strpos($key, '.') === FALSE){
            return isset($this->source[$key])? $this->source[$key]: $default;
        }
        
        $keys = explode('.', $key);
        $result = $this->source;
        foreach ($keys as $k) {
            if (isset($result[$k])) {
                $result = $result[$k];
            } else {
                $result = $default;
                break;
            }
        }
        
        return $result;
    }

    public function set($key, $value) {
        $keys = explode('.', $key);
        $lk = array_pop($keys);
        $l = &$this->source;
        foreach ($keys as $k) {
            if (!isset($l[$k])) {
                $l[$k] = array();
            }

            $l = &$l[$k];
        }

        $l[$lk] = $value;
    }

    public function remove($key) {
        $keys = explode('.', $key);
        $lk = array_pop($keys);
        $l = &$this->source;
        foreach ($keys as $k) {
            $l = &$l[$k];
        }

        unset($l[$lk]);
        return $this;
    }

    public function offsetExists($offset) {
        return isset($this->source[$offset]);
    }

    public function offsetGet($offset) {
        return $this->get($offset);
    }

    public function offsetSet($offset, $value) {
        $this->set($value, $offset);
    }

    public function offsetUnset($offset) {
        $this->remove($offset);
    }

}